#!/bin/bash
# Avaliable environment:
#
# Download variable:
# WEB_URL=
# GIT_URL=

. $TONE_ROOT/lib/testinfo.sh
. $TONE_ROOT/lib/common.sh
nr_open_default=$(cat /proc/sys/fs/nr_open)


get_keentune_code()
{
    cd $TONE_BM_RUN_DIR/
    rm -rf keentune-bench

    if [ "$code_source" == "gitee" ];then
        keentune_bench_addr="https://gitee.com/anolis/keentune_bench.git"
        git clone $keentune_bench_addr
        mv keentune_bench keentune-bench
        cd keentune-bench && git checkout $test_branch -f || return 1
        cd ..
    else
        return 1
    fi
}

build_keentune()
{
    cd $TONE_BM_RUN_DIR/
    cd keentune-bench
    python3 setup.py install
    cd $TONE_BM_RUN_DIR/
}

clear_keentune_env()
{
    rm -rf /usr/local/lib/python3.6/site-packages/keentune*
    rm -rf /usr/local/lib/python3.6/site-packages/brain
    rm -rf /usr/local/lib/python3.6/site-packages/target
    rm -rf /usr/local/lib/python3.6/site-packages/bench
    rm -f /usr/local/bin/keentune*
    ps -ef|grep -E 'keentuned|keentune-brain|keentune-target|keentune-bench'|grep -v grep|awk '{print $2}'| xargs -I {} kill -9 {}
}

clear_log_files()
{
    rm -rf /var/log/bench*
    rm -rf /var/log/brain*
    rm -rf /var/log/target*
    rm -rf /var/log/keentune*
    rm -rf /var/keentune/backup/param_set*
}

setup()
{
    logger clear_keentune_env
    logger clear_log_files
    logger "get_keentune_code || exit 1"
    logger "build_keentune || exit 1"
}

run_fail()
{
    cp $TONE_BM_RUN_DIR/keentune-bench-$log_suffix $TONE_CURRENT_RESULT_DIR/
    exit 1
}

run()
{
    cd $TONE_BM_RUN_DIR/
    log_suffix="$code_source-$test_branch-log-$(date +"%Y-%m-%d-%H-%M-%S")"
    keentune-bench > keentune-bench-$log_suffix 2>&1 &

    sleep 5
    ps -ef|grep -w keentune-bench | grep -v grep || run_fail
    
    logger cd $TONE_BM_RUN_DIR/keentune-bench/test

    echo -e "Start test:python3 main.py\nTests will take several minutes, pls wait"
    python3 main.py
    if [ $? -ne 0 ]; then
        cd $TONE_BM_RUN_DIR/
        echo "ERROR:python3 main.py failed"
        run_fail
    fi

    cd $TONE_BM_RUN_DIR/
}

parse()
{
    awk -f $TONE_BM_SUITE_DIR/parse.awk
}

teardown()
{
    clear_keentune_env
    [ -n "$nr_open_default" ] && sysctl -w fs.nr_open=$nr_open_default
}
